package com.suoluo.zenadmin.service.home;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.suoluo.zenadmin.common.CommonResp;
import com.suoluo.zenadmin.common.JSONPageData;
import com.suoluo.zenadmin.common.PageUtil;
import com.suoluo.zenadmin.common.StringUtil;
import com.suoluo.zenadmin.common.config.SystemConfigHolder;
import com.suoluo.zenadmin.dao.home.HomeDAO;
import com.suoluo.zenadmin.service.ServiceException;
import com.suoluo.zenadmin.service.dest.DestFeatureCategoryService;
import com.suoluo.zenadmin.vo.PageVO;
import com.suoluo.zenadmin.vo.dest.DestFeatureCategoryVO;
import com.suoluo.zenadmin.vo.home.HomeCategoryVO;
import com.suoluo.zenadmin.vo.home.HomeItemPortalVO;
import com.suoluo.zenadmin.vo.home.HomeItemVO;

public class HomeServiceImpl implements HomeService{

	private static Log logger = LogFactory.getLog(HomeServiceImpl.class);
	@Autowired
	private HomeDAO homeDAO;
	
	@Resource(name="categoryService")
	private DestFeatureCategoryService categoryService;
	
	@Override
	public List<HomeCategoryVO> findListHomeCategory() {
		return homeDAO.findListHomeCategory();
	}

	@Override
	public void saveHomeCategory(HomeCategoryVO categoryPOJO) {
		
		int featureCategoryId = categoryPOJO.getFeatureCategoryId();
		int res = homeDAO.findHomeCategoryByCategoryId(featureCategoryId);
		if(res > 0)
		{
			throw new ServiceException(CommonResp.FAIL_CODE,"该类别首页已添加过了！请继续你需要的操作！");
		}
		DestFeatureCategoryVO destCategory = categoryService.findDestFeatureCategoryById(featureCategoryId);
		categoryPOJO.setCategoryName(destCategory.getFeatureCategoryName());
		homeDAO.saveHomeCategory(categoryPOJO);
	}

	@Override
	public HomeCategoryVO findHomeCategoryById(int categoryId) {
		return homeDAO.findHomeCategoryById(categoryId);
	}

	@Override
	public void updateHomeCategory(HomeCategoryVO categoryPOJO) {
		homeDAO.updateHomeCategory(categoryPOJO);
	}

	@Override
	public void deleteHomeCategory(int categoryId) {
		//先删除首页项
		homeDAO.deleteHomeItemByCategoryId(categoryId);
		//在删除首页类别
		homeDAO.deleteHomeCategory(categoryId);
	}


	@Override
	public List<DestFeatureCategoryVO> findListFeatureCategory() {
		return homeDAO.findListFeatureCategory();
	}


	@SuppressWarnings("rawtypes")
	@Override
	public List<Map> findListHomeCategoryItem(int categoryId) {
		
		//获取首页新闻特色类别Id
		int homeNewsFeatureCategoryId = SystemConfigHolder.getHomeNewsFeatureCategoryId();
		//获取首页新闻特色类别Id
		int homeDestFeatureCategoryId = SystemConfigHolder.getHomeDestFeatureCategoryId();
		//获取首页新闻特色类别Id
		int homeHotelFeatureCategoryId = SystemConfigHolder.getHomeHotelFeatureCategoryId();
		
		HomeCategoryVO homeCategory = homeDAO.findHomeCategoryById(categoryId);
		
		if(homeCategory.getFeatureCategoryId() == homeNewsFeatureCategoryId)
		{
			return homeDAO.findListNewsHomeItem(categoryId);
		}
		else if(homeCategory.getFeatureCategoryId() == homeDestFeatureCategoryId)
		{
			return homeDAO.findListDestHomeItem(categoryId);
		}
		else if(homeCategory.getFeatureCategoryId() == homeHotelFeatureCategoryId)
		{
			return homeDAO.findListHotelHomeItem(categoryId);
		}
		else
		{
			return homeDAO.findListHomeItem(categoryId);
		}
	}

	@Override
	public JSONPageData findAddFeatureCategoryList(PageVO page,int featureCategoryId,String tempName) {
		//获取首页新闻特色类别Id
		int homeNewsFeatureCategoryId = SystemConfigHolder.getHomeNewsFeatureCategoryId();
		//获取首页目的地特色类别Id
		int homeDestFeatureCategoryId = SystemConfigHolder.getHomeDestFeatureCategoryId();
		//获取首页酒店特色类别Id
		int homeHotelFeatureCategoryId = SystemConfigHolder.getHomeHotelFeatureCategoryId();
		
		//获得页面的分页参数
		int currPage = page.getPage();
		int rows = page.getRows();
		int startPage = PageUtil.calcStartRow(currPage, rows);
		
		//除新闻以外，目的地、酒店、特色项、都可根据目的地名称去查询过滤勾选项
		
		if(featureCategoryId == homeNewsFeatureCategoryId)
		{
			//勾选新闻信息
			return queryAllNewsImgTitle(startPage,rows,homeNewsFeatureCategoryId,tempName);
		}
		else if(featureCategoryId == homeDestFeatureCategoryId)
		{
			//勾选目的地探索信息
			return queryAllDestImgTitle(startPage,rows,homeDestFeatureCategoryId,tempName);
		}
		else if(featureCategoryId == homeHotelFeatureCategoryId)
		{
			//勾选酒店精选信息
			return queryAllHotelNewsImgTitle(startPage, rows,homeHotelFeatureCategoryId,tempName);
		}
		else
		{
			//根据featureCategoryId到目的地特色项表中查询对应的记录
			return queryAllFeatureItem(startPage, rows,tempName,featureCategoryId);
		}
	}
	/**
	 * 首页勾选新闻类型的数据时
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	public JSONPageData queryAllNewsImgTitle(int startPage,int rows,int homeCategoryId,String tempName) {
		
		JSONPageData data = new JSONPageData();
		tempName = changeTempName(tempName);
		// 查询总的新闻图文信息
		List<Map> list = homeDAO.findNewsHome(startPage, rows,homeCategoryId,tempName);
		data.setRows(list);
		// 查询新闻图文信息总数
		int total = homeDAO.findNewsCount(tempName);
		data.setTotal(total);
		
		return data;
	}

	/**
	 * 查询所有的目的地信息
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	public JSONPageData queryAllDestImgTitle(int startPage,int rows,int homeCategoryId,String tempName) {
		JSONPageData data = new JSONPageData();
		tempName = changeTempName(tempName);
		// 查询总的目的地信息
		List<Map> list = homeDAO.findDestHomeImg(startPage, rows,homeCategoryId,tempName);
		data.setRows(list);
		// 查询新闻图文信息总数
		int total = homeDAO.findDestCount(tempName);
		data.setTotal(total);
		return data;
	}

	/**
	 * 查询所有酒店图文新闻信息
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	public JSONPageData queryAllHotelNewsImgTitle(int startPage,int rows,int homeCategoryId,String tempName) {
		JSONPageData data = new JSONPageData();
		tempName = changeTempName(tempName);
		// 查询酒店图文新闻信息
		List<Map> list = homeDAO.findHotelHome(startPage, rows,homeCategoryId,tempName);
		data.setRows(list);
		// 查询酒店新闻总数
		int total = homeDAO.findHotelCount(tempName);
		data.setTotal(total);
		return data;
	}
	/**
	 * 根据特色类别id查询所有的特色项信息
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	public JSONPageData queryAllFeatureItem(int startPage,int rows,String tempName,int featureCategoryId)
	{
		JSONPageData data = new JSONPageData();
		tempName = changeTempName(tempName);
		// 查询所有的特色项信息
		List<Map> list = homeDAO.findFeatureItemByFeatureCategoryId(startPage, rows,tempName,featureCategoryId);
		data.setRows(list);
		// 查询所有特色项总数
		int total = homeDAO.findFeatureCategoryCount(featureCategoryId,tempName);
		data.setTotal(total);
		return data;
	}
	/**
	 * 勾选首页项时初始化数据，封装查询条件
	 * @param tempName
	 * @return
	 */
	private String changeTempName(String tempName)
	{
		if(StringUtils.hasLength(tempName))
		{
			tempName = "%"+tempName+"%";
		}
		else
		{
			tempName = null;
		}
		return tempName;
	}

	@Override
	public void saveHomeCategoryItem(HomeItemVO itemVO) {

		String action = itemVO.getCheckInfo();
		int  homeParaId = itemVO.getItemId();

		try {
			
			itemVO.setItemCreateTime(new Date());
			
			if (action == null && homeParaId != 0) {
				// 删除该选中信息
				homeDAO.deleteHomeItem(homeParaId);
			} else {
				homeDAO.saveHomeItem(itemVO);
			}
		} catch (Exception e) {
			logger.error("fail to checkHomeInfo", e);
			throw new ServiceException(CommonResp.FAIL_CODE,"首页勾选特色类别项失败！");
		}
	}
	
	@Override
	public List<HomeCategoryVO> findAllHomeData() {

		@SuppressWarnings("rawtypes")
		List<Map> result = homeDAO.findAllHomeData();
		Map<Integer, HomeCategoryVO> categoryMap = new HashMap<Integer, HomeCategoryVO>();

		for (Map<String, Object> row : result) {
			Integer featureCategoryId = (Integer) row
					.get("t_feature_category_id");
			HomeCategoryVO categoryVO = categoryMap.get(featureCategoryId);
			if (categoryVO == null) {
				categoryVO = new HomeCategoryVO();
				categoryVO.setFeatureCategoryId(featureCategoryId);
				String categoryName = (String) row.get("t_category_name");
				categoryVO.setCategoryName(categoryName);
				Timestamp updateTime = (Timestamp) row
						.get("t_category_update_time");
				categoryVO.setCategoryUpdateTime(updateTime);
				categoryMap.put(featureCategoryId, categoryVO);
			}
			HomeItemPortalVO itemVO = new HomeItemPortalVO();
			itemVO.setDestId((Integer) row.get("t_dest_id"));
			itemVO.setLinkId((Integer) row.get("t_link_id"));
			String zhname = (String) row.get("zhname");
			itemVO.setZhname(zhname);
			String enname = (String) row.get("enname");
			itemVO.setTitle(StringUtil.buildCompleteName(zhname, enname));
			String desc = (String) row.get("summary");
			// desc = UBB.clear(desc);
			// int descLimit = SystemConfigHolder.getImageBlockContentLimit();
			// if (desc.length() > descLimit){
			// desc = desc.substring(0, descLimit);
			// }
			itemVO.setDesc(desc);
//			itemVO.setImgPreffix((String) row.get("t_feature_item_img_preffix"));
//			itemVO.setImgName((String) row.get("t_feature_item_img"));
			String source = (String) row.get("source");
			String small = (String) row.get("small");
			String normal = (String) row.get("normal");
			itemVO.setOrigImg(source + normal);
			itemVO.setMiniImg(source+small);
			categoryVO.addHomeItem(itemVO);
		}
		List<HomeCategoryVO> categoryList = new ArrayList<HomeCategoryVO>(
				categoryMap.values());
		Collections.sort(categoryList);
		return categoryList;
	}
}
